// pages/user-management/index.tsx
import React, { useState } from "react";
import { request } from "@/utils/request";
import { message } from "antd";
import OSSFileSelector from "./components/OSSFileSelector";
import FilePreview from "./components/FilePreview";

const UpAiPersionData: React.FC = () => {
  const [form, setForm] = useState({
    // 基本信息
    avatar: "",
    image: "", // 新增：主图字段
    username: "",
    likes: "",
    comments: "",
    isPremium: false,
    description: "",
    images: [] as string[],
    videos: [] as string[],
    age: 18,
    type: "Girl",
    gender: "",
    occupation: "",
    zodiac: "",
    birthday: "", // 新增：生日字段
    language: "English",
    country: "JP", // 新增：国家字段，默认选中日本

    // character_profiles
    promptWord: "",
    work_flow: "AS1-G001",
    aiPersion_id: 0,
    persionImageDescription: "", // 新增：角色图片提示词
    
    // voice_settings
    gpt_path: "GPT_weights_v4/zbs001.ckpt",
    sovits_path: "SoVITS_weights_v4/jm003.pth",
    text_language: "ja",
    refer_wav_path: "",
    prompt_language: "ja",
    
    // Emotions
    emotions_list: [
      {
        name: "default",
        path: "Voice/Ref/001-默认.wav",
        prompt_text: "あら、いつからそんな気遣いができるようになったのかしら。"
      }
    ] as Array<{name: string, path: string, prompt_text: string}>,
  });
  const [loading, setLoading] = useState(false);
  const [uploadedContent, setUploadedContent] = useState(""); // 用于存储上传文件的内容
  const [isDragOver, setIsDragOver] = useState(false); // 拖拽状态

  // 重置表单到初始状态
  const resetForm = () => {
    setForm({
      avatar: "",
      image: "",
      username: "",
      likes: "",
      comments: "",
      isPremium: false,
      description: "",
      images: [] as string[],
      videos: [] as string[],
      age: 18,
      type: "Girl",
      gender: "",
      occupation: "",
      zodiac: "",
      birthday: "",
      language: "English",
      country: "JP",
      promptWord: "",
      work_flow: "AS1-G001",
      aiPersion_id: 0,
      persionImageDescription: "",
      gpt_path: "GPT_weights_v4/zbs001.ckpt",
      sovits_path: "SoVITS_weights_v4/jm003.pth",
      text_language: "ja",
      refer_wav_path: "",
      prompt_language: "ja",
      emotions_list: [
        {
          name: "default",
          path: "Voice/Ref/001-默认.wav",
          prompt_text: "あら、いつからそんな気遣いができるようになったのかしら。"
        }
      ],
    });
    setUploadedContent("");
    setIsDragOver(false);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    setForm((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? (e.target as HTMLInputElement).checked :
        type === "number" ? Number(value) : value,
    }));
  };

  // 处理富文本编辑器内容变化
  const handleRichTextChange = (content: string) => {
    setForm((prev) => ({
      ...prev,
      promptWord: content,
    }));
  };

  // 自动调整textarea高度
  const handleTextareaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const { name, value } = e.target;

    // 自动调整高度
    e.target.style.height = 'auto';
    e.target.style.height = e.target.scrollHeight + 'px';

    // 更新状态
    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  // 处理emotions_list数组变化
  const handleEmotionChange = (idx: number, field: 'name' | 'path' | 'prompt_text', value: string) => {
    setForm((prev) => ({
      ...prev,
      emotions_list: prev.emotions_list.map((item, i) =>
        i === idx ? { ...item, [field]: value } : item
      ),
    }));
  };

  // 添加emotion项
  const addEmotion = () => {
    setForm((prev) => ({
      ...prev,
      emotions_list: [...prev.emotions_list, { name: "", path: "", prompt_text: "" }],
    }));
  };

  // 删除emotion项
  const removeEmotion = (idx: number) => {
    setForm((prev) => ({
      ...prev,
      emotions_list: prev.emotions_list.filter((_, i) => i !== idx),
    }));
  };

  const handleArrayChange = (key: string, idx: number, value: string) => {
    setForm((prev) => ({
      ...prev,
      [key]: (prev as any)[key].map((v: string, i: number) => (i === idx ? value : v)),
    }));
  };

  const addArrayItem = (key: string) => {
    setForm((prev) => ({
      ...prev,
      [key]: [...(prev as any)[key], ""],
    }));
  };

  const removeArrayItem = (key: string, idx: number) => {
    setForm((prev) => ({
      ...prev,
      [key]: (prev as any)[key].filter((_: string, i: number) => i !== idx),
    }));
  };

  // 删除单个文件（用于单选字段）
  const removeSingleFile = (fieldName: string) => {
    setForm((prev) => ({
      ...prev,
      [fieldName]: "",
    }));
  };

  // 删除数组中的文件（用于多选字段）
  const removeFileFromArray = (fieldName: string, urlToRemove: string) => {
    setForm((prev) => ({
      ...prev,
      [fieldName]: (prev as any)[fieldName].filter((url: string) => url !== urlToRemove),
    }));
  };

  // 验证文件类型
  const validateFile = (file: File) => {
    const allowedTypes = ['text/plain', 'text/markdown', 'application/x-markdown'];
    const isMarkdown = file.name.endsWith('.md') || file.name.endsWith('.markdown');

    if (!allowedTypes.includes(file.type) && !isMarkdown) {
      message.error('只支持 text 或 markdown 格式的文件');
      return false;
    }
    return true;
  };

  // 处理文件读取
  const processFile = (file: File) => {
    if (!validateFile(file)) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target?.result as string;
      setUploadedContent(content);
      // 将文件内容填充到富文本编辑器
      setForm((prev) => ({
        ...prev,
        promptWord: content,
      }));

      // 延迟调整textarea高度，确保内容已更新
      setTimeout(() => {
        const textarea = document.querySelector('textarea[name="promptWord"]') as HTMLTextAreaElement;
        if (textarea) {
          textarea.style.height = 'auto';
          textarea.style.height = textarea.scrollHeight + 'px';
        }
      }, 0);

      message.success('文件内容已成功加载到编辑器');
    };
    reader.readAsText(file);
  };

  // 处理文件上传 (text/markdown)
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    processFile(file);
  };

  // 处理拖拽进入
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(true);
  };

  // 处理拖拽离开
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
  };

  // 处理拖拽悬停
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };

  // 处理文件拖拽放下
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);

    const files = e.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0];
      processFile(file);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const data = {
        information: {
          name: form.username.trim(),
          age: Number(form.age),
          gender: form.gender.trim(),
          occupation: form.occupation.trim(),
          zodiac: form.zodiac.trim(),
          birthday: form.birthday.trim(),
          language: form.language,
        },
        country: form.country,
        avatar: form.avatar.trim(),
        image: form.image.trim(),
        likes: form.likes.trim(),
        comments: form.comments.trim(),
        is_premium: form.isPremium,
        description: form.description.trim(),
        images: form.images.map(i => i.trim()).filter(Boolean),
        videos: form.videos.map(i => i.trim()).filter(Boolean),
        character_profiles: {
          Emotions: {
            Emotions_list: form.emotions_list.filter(item => item.name.trim() && item.path.trim() && item.prompt_text.trim())
          },
          work_flow: form.work_flow,
          promptWord: form.promptWord.trim(),
          aiPersion_id: form.aiPersion_id,
          voice_settings: {
            text: "",
            gpt_path: form.gpt_path.trim(),
            prompt_text: "",
            sovits_path: form.sovits_path.trim(),
            text_language: form.text_language,
            refer_wav_path: form.refer_wav_path.trim(),
            prompt_language: form.prompt_language,
          },
          persionImageDescription: form.persionImageDescription.trim(),
        },
        type: form.type.trim(),
      };

      const res = await request.post("/api/ai-persons/addPerson", data);
      console.log('提交到后端的数据', res);
      if (res.data.message === 'AI人物创建成功') {
        resetForm();
      }
      message.success("创建成功！");
    } catch (err: any) {
      message.error(err?.response?.data?.message || "创建失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-full max-w-7xl mx-auto bg-white rounded-2xl shadow-lg p-8 my-8">
      <h2 className="text-3xl font-bold text-center text-gray-800 mb-8">创建新的AI人物</h2>

      <form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 基本信息区域 */}
        <div className="lg:col-span-2">
          <h3 className="text-xl font-semibold text-gray-800 mb-6 border-b pb-2">基本信息</h3>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">头像URL</label>
              <OSSFileSelector
                value={form.avatar}
                onChange={(value) => setForm(prev => ({ ...prev, avatar: value as string }))}
                placeholder="选择头像文件"
              />
              <FilePreview
                files={form.avatar}
                multiple={false}
                onRemove={() => removeSingleFile('avatar')}
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">主图URL</label>
              <OSSFileSelector
                value={form.image}
                onChange={(value) => setForm(prev => ({ ...prev, image: value as string }))}
                placeholder="选择主图文件"
              />
              <FilePreview
                files={form.image}
                multiple={false}
                onRemove={() => removeSingleFile('image')}
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">人设名</label>
              <input
                name="username"
                value={form.username}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                required
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">年龄</label>
              <input
                name="age"
                type="number"
                min={1}
                value={form.age}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                required
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">性别</label>
              <input
                name="gender"
                value={form.gender}
                onChange={handleChange}
                placeholder="如：女"
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">职业</label>
              <input
                name="occupation"
                value={form.occupation}
                onChange={handleChange}
                placeholder="如：学生"
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">星座</label>
              <input
                name="zodiac"
                value={form.zodiac}
                onChange={handleChange}
                placeholder="如：金牛座"
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">生日</label>
              <input
                name="birthday"
                value={form.birthday}
                onChange={handleChange}
                placeholder="如：9月26日"
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">语言</label>
              <select
                name="language"
                value={form.language}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="Chinese">Chinese</option>
                <option value="English">English</option>
                <option value="Japanese">Japanese</option>
              </select>
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">国家</label>
              <select
                name="country"
                value={form.country}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="JP">日本</option>
                <option value="EN">欧美</option>
              </select>
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">点赞数</label>
              <input
                name="likes"
                value={form.likes}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                required
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">评论数</label>
              <input
                name="comments"
                value={form.comments}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                required
              />
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">是否为高级（isPremium）</label>
              <select
                name="isPremium"
                value={form.isPremium ? "true" : "false"}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              >
                <option value="false">否</option>
                <option value="true">是</option>
              </select>
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">类型（type）</label>
              <select
                name="type"
                value={form.type}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              >
                <option value="Girl">Girl</option>
                <option value="Man">Man</option>
                <option value="AnimeGirl">AnimeGirl</option>
                <option value="AnimeMan">AnimeMan</option>
              </select>
            </div>

            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">AI人物ID</label>
              <input
                name="aiPersion_id"
                type="number"
                min={0}
                value={form.aiPersion_id}
                onChange={handleChange}
                placeholder="请输入AI人物ID"
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              />
            </div>

            <div className="flex flex-col lg:col-span-2">
              <label className="mb-2 font-medium text-gray-700">背景（description）</label>
              <textarea
                name="description"
                value={form.description}
                onChange={handleChange}
                className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all min-h-[100px]"
                required
              />
            </div>
          </div>
        </div>

        {/* 媒体文件区域 */}
        <div className="lg:col-span-2">
          <h3 className="text-xl font-semibold text-gray-800 mb-6 border-b pb-2">媒体文件</h3>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 图片数组 */}
            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">图片数组</label>
              <OSSFileSelector
                value={form.images}
                onChange={(value) => setForm(prev => ({ ...prev, images: value as string[] }))}
                multiple={true}
                placeholder="选择图片文件（可多选）"
              />
              <FilePreview
                files={form.images}
                multiple={true}
                onRemove={(url) => removeFileFromArray('images', url)}
              />
            </div>

            {/* 视频数组 */}
            <div className="flex flex-col">
              <label className="mb-2 font-medium text-gray-700">视频数组</label>
              <OSSFileSelector
                value={form.videos}
                onChange={(value) => setForm(prev => ({ ...prev, videos: value as string[] }))}
                multiple={true}
                placeholder="选择视频文件（可多选）"
              />
              <FilePreview
                files={form.videos}
                multiple={true}
                onRemove={(url) => removeFileFromArray('videos', url)}
              />
            </div>
          </div>
        </div>

        {/* character_profiles 区域 */}
        <div className="lg:col-span-2">
          <h3 className="text-xl font-semibold text-gray-800 mb-6 border-b pb-2">角色设定</h3>

          <fieldset className="border border-gray-300 rounded-xl p-6 mb-6">
            <legend className="px-2 text-blue-600 font-medium">Character Profiles</legend>

            {/* 富文本编辑器 */}
            <div className="mb-6">
              <label className="block mb-2 font-medium text-gray-700">角色提示词（PromptWord）</label>
              <textarea
                name="promptWord"
                value={form.promptWord}
                onChange={handleTextareaChange}
                placeholder="请输入角色的详细描述和提示词..."
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm resize-none overflow-hidden"
                style={{ minHeight: '60px' }}
              />
            </div>

            {/* 文件上传区域 */}
            <div className="mb-6">
              <label className="block mb-2 font-medium text-gray-700">上传文本文件（支持 .txt 或 .md 格式）</label>
              <div
                className={`border-2 border-dashed rounded-lg p-6 transition-all ${isDragOver
                  ? 'border-blue-400 bg-blue-50'
                  : 'border-gray-300 hover:border-gray-400'
                  }`}
                onDragEnter={handleDragEnter}
                onDragLeave={handleDragLeave}
                onDragOver={handleDragOver}
                onDrop={handleDrop}
              >
                <div className="text-center">
                  <div className="mb-4">
                    <svg
                      className={`mx-auto h-12 w-12 ${isDragOver ? 'text-blue-400' : 'text-gray-400'}`}
                      stroke="currentColor"
                      fill="none"
                      viewBox="0 0 48 48"
                    >
                      <path
                        d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                        strokeWidth={2}
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  </div>
                  <div className="mb-4">
                    <label htmlFor="file-upload" className="cursor-pointer">
                      <span className={`text-sm font-medium ${isDragOver ? 'text-blue-600' : 'text-blue-600 hover:text-blue-500'}`}>
                        点击上传文件
                      </span>
                      <input
                        id="file-upload"
                        type="file"
                        accept=".txt,.md,.markdown,text/plain,text/markdown"
                        onChange={handleFileUpload}
                        className="sr-only"
                      />
                    </label>
                    <span className="text-sm text-gray-500"> 或拖拽文件到此处</span>
                  </div>
                  <p className="text-xs text-gray-500">
                    支持 TXT 和 Markdown 格式，文件内容将自动填充到角色提示词输入框
                  </p>
                  {isDragOver && (
                    <p className="text-xs text-blue-600 mt-2 font-medium">
                      松开鼠标即可上传文件
                    </p>
                  )}
                </div>
              </div>
            </div>

            {/* 声音设置 */}
            <div className="mb-6">
              <label className="block mb-2 font-medium text-gray-700">声音设置</label>
              <div className="pl-4 border-l-2 border-blue-200 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <div>
                  <label className="block mb-1 text-sm text-gray-600">GPT路径</label>
                  <input
                    name="gpt_path"
                    value={form.gpt_path}
                    onChange={handleChange}
                    placeholder="GPT权重路径"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block mb-1 text-sm text-gray-600">SoVITS路径</label>
                  <input
                    name="sovits_path"
                    value={form.sovits_path}
                    onChange={handleChange}
                    placeholder="SoVITS权重路径"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block mb-1 text-sm text-gray-600">参考音频路径</label>
                  <input
                    name="refer_wav_path"
                    value={form.refer_wav_path}
                    onChange={handleChange}
                    placeholder="参考音频路径"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block mb-1 text-sm text-gray-600">文本语言</label>
                  <select
                    name="text_language"
                    value={form.text_language}
                    onChange={handleChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="ja">日语</option>
                    <option value="en">英语</option>
                    <option value="zh">中文</option>
                  </select>
                </div>
                <div>
                  <label className="block mb-1 text-sm text-gray-600">提示词语言</label>
                  <select
                    name="prompt_language"
                    value={form.prompt_language}
                    onChange={handleChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="ja">日语</option>
                    <option value="en">英语</option>
                    <option value="zh">中文</option>
                  </select>
                </div>
              </div>
            </div>

            {/* 情感配置 */}
            <div className="mb-6">
              <label className="block mb-2 font-medium text-gray-700">情感配置</label>
              <div className="pl-4 border-l-2 border-blue-200">
                {form.emotions_list.map((item, idx) => (
                  <div key={idx} className="mb-4 p-4 border border-gray-200 rounded-lg">
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                      <div>
                        <label className="block mb-1 text-sm text-gray-600">情感名称</label>
                        <input
                          value={item.name}
                          onChange={e => handleEmotionChange(idx, 'name', e.target.value)}
                          placeholder="如：default, smile, happy"
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        />
                      </div>
                      <div>
                        <label className="block mb-1 text-sm text-gray-600">音频路径</label>
                        <input
                          value={item.path}
                          onChange={e => handleEmotionChange(idx, 'path', e.target.value)}
                          placeholder="如：Voice/Ref/001-默认.wav"
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        />
                      </div>
                      <div>
                        <label className="block mb-1 text-sm text-gray-600">提示词文本</label>
                        <textarea
                          value={item.prompt_text}
                          onChange={e => handleEmotionChange(idx, 'prompt_text', e.target.value)}
                          placeholder="情感对应的提示词文本"
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                          rows={2}
                        />
                      </div>
                    </div>
                    <div className="mt-2 flex justify-end">
                      <button
                        type="button"
                        className="px-3 py-1 text-red-600 border border-red-300 rounded-lg hover:bg-red-50 transition-all text-sm"
                        onClick={() => removeEmotion(idx)}
                        disabled={form.emotions_list.length === 1}
                      >
                        删除情感
                      </button>
                    </div>
                  </div>
                ))}
                <button
                  type="button"
                  className="px-4 py-2 text-blue-600 border border-blue-300 rounded-lg hover:bg-blue-50 transition-all"
                  onClick={addEmotion}
                >
                  添加情感
                </button>
              </div>
            </div>

            {/* 图片模型 */}
            <div className="mb-6">
              <label className="block mb-2 font-medium text-gray-700">图片模型</label>
              <select
                name="work_flow"
                value={form.work_flow}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="AS1-G001">AS1-G001</option>
                <option value="AS1">AS1</option>
                <option value="AS2">AS2</option>
                <option value="AS3">AS3</option>
              </select>
            </div>

            {/* 角色图片提示词 */}
            <div className="mb-6">
              <label className="block mb-2 font-medium text-gray-700">角色图片提示词<span style={{ fontWeight: "600" }} className="text-[red]">（没有则禁止填写 !）</span></label>
              <textarea
                name="persionImageDescription"
                value={form.persionImageDescription}
                onChange={handleTextareaChange}
                placeholder="请输入角色图片生成的提示词...(没有则禁止填写）"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none overflow-hidden"
                style={{ minHeight: '60px' }}
              />
            </div>
          </fieldset>
        </div>

        <div className="lg:col-span-2 flex justify-center mt-8">
          <button
            type="submit"
            className="bg-blue-600 hover:bg-blue-700 text-white font-medium px-12 py-3 rounded-lg shadow-lg hover:shadow-xl transition-all transform hover:-translate-y-0.5 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
            disabled={loading}
          >
            {loading ? "提交中..." : "提交"}
          </button>
        </div>
      </form>
    </div>
  );
};

export default UpAiPersionData;
